package com.code.demo.mvp.base;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.code.demo.ui.common.ToastFactory;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by yangliguo on 2019/3/1.
 */

public abstract class BaseMvpFragment<T extends IPresenter> extends Fragment implements IView {

    private View parentView;
    protected Activity activity;
    protected T presenter;

    private Unbinder unbinder;

    public abstract int getLayoutResId();

    public abstract T createPresenter();

    public abstract void finishCreateView(Bundle savedInstanceState);

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        presenter = createPresenter();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        parentView = inflater.inflate(getLayoutResId(), container, false);

        unbinder = ButterKnife.bind(this, parentView);

        activity = getActivity();

        return parentView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        if (presenter != null) {
            presenter.attachView(this);
        }

        finishCreateView(savedInstanceState);
    }

    @Override
    public void onDetach() {
        super.onDetach();

        unbinder.unbind();

        activity = null;
    }

    @Override
    public void onDestroy() {

        if (presenter != null) {
            presenter.onDestroy();
        }
        presenter = null;

        super.onDestroy();
    }

    @Override
    public void showError(String msg) {
        ToastFactory.showToast(activity, msg);
    }

    @Override
    public void handleException(Exception e) {
        e.printStackTrace();
        hideLoading();
        showError(e.getMessage());
    }
}
